<template>
  <div class="image-upload">
    <el-upload
      list-type="picture-card"
      action=""
      :file-list="fileList"
      :on-preview="preview"
      :limit="limit"
      :class="{disabled:isDisabled}"
      :on-remove="handleRemove"
      :http-request="upload"
      :on-change="handleChange"
      :before-upload="handleBeforeUpload"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <!-- 进度条 -->
    <!-- <el-progress :percentage="precent" status="success" /> -->
    <!-- 预览图片的弹框 -->
    <el-dialog width="600px" top="8vh" title="图片预览" :visible.sync="showDialog" @close="showDialog = false">
      <img width="100%" :src="imgUrl" alt="">
    </el-dialog>
  </div>
</template>
<script>
import COS from 'cos-js-sdk-v5' // 导入腾讯云的包(sdk)
const cos = new COS({
  SecretId: 'AKIDxjFUTBcmfHcfRxCArJUTCepjMhma8OO7', // 身份识别ID
  SecretKey: 'VjgNnxqTpuiGXWEfqlVzDAqFOFp89uNZ' // 身份秘钥
})
export default {
  name: 'Imageupload',
  data() {
    return {
      fileList: [
        // { url: 'https://img0.baidu.com/it/u=3311900507,1448170316&fm=26&fmt=auto&gp=0.jpg' },
        // { url: 'https://img0.baidu.com/it/u=2135557883,423992380&fm=26&fmt=auto&gp=0.jpg' }
      ],
      showDialog: false,
      limit: 2,
      precent: 0,
      imgUrl: ''
    }
  },
  computed: {
    isDisabled() {
      return this.fileList.length >= this.limit
    },
    // 解决bug：上传还没成功，就可以保存
    isAllUploadSuccess() {
      return this.fileList.every(item => item.status === 'success')
    }
  },
  methods: {
    // ===== 图片预览 ====
    preview(file) {
      this.showDialog = true
      this.imgUrl = file.url
    },
    // ====== 删除图片 ======
    handleRemove(file, fileList) {
      // this.fileList = [...fileList] // 方法一：将结构中的fileList展开，依次存储
      this.fileList = this.fileList.filter(item => item.uid !== file.uid)
    },
    // ====== 上传文件前的校验 ======
    handleBeforeUpload(file) {
      // 1. 限制文件类型 file.type
      const types = ['image/jpeg', 'image/gif', 'image/bmp', 'image/png']
      if (!types.includes(file.type)) {
        this.$message.error('上传的图片格式, 必须是jpg, gif, bmp, png的格式!')
        return false
      }
      // 2. 限制文件大小 file.size
      if (file.size / 1024 / 1024 >= 5) {
        this.$message.error('上传头像过大, 超过了5M, 必须5M以内')
        return false
      }
      return true
    },
    // ====== 上传图片 =====
    upload(obj) {
      const fileObj = this.fileList.find(item => item.uid === obj.file.uid)
      fileObj.status = 'uploading'
      // * 这里请求的不是后台，是腾讯云服务器
      // 执行上传操作
      cos.putObject({
        Bucket: 'back-stage-84-1306637832', /* 存储桶 */
        Region: 'ap-shanghai', /* 存储桶所在地域，必须字段 */
        Key: obj.file.name, /* 文件名 */
        StorageClass: 'STANDARD', // 上传模式, 标准模式
        Body: obj.file, // 上传文件对象
        onProgress: (progressData) => {
          fileObj.precentage = parseInt(progressData.precent * 100)
        }
      }, (err, data) => {
        if (err) return console.log(err)
        if (data.statusCode === 200) {
          // console.log('地址:', 'https://' + data.Location)
          // console.log('uid:', params.file.uid)
          // 找到对应的上传的这个file的项
          const fileObj = this.fileList.find(item => item.uid === obj.file.uid)

          // 修改地址
          fileObj.url = 'https://' + data.Location
          // 更新状态
          setTimeout(() => {
            fileObj.status = 'success'
          }, 100)
        }
        console.log(data)
      })
    },
    // 选择文件、上传文件成功/失败 ==> 结构与数据同步
    handleChange(file, fileList) {
      this.fileList = [...fileList]
    }
  }
}
</script>
<style lang='scss' scoped>
.disabled{
  ::v-deep{
    .el-upload-picture-card{
      display: none;
    }
  }
}
</style>
